﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Data;
using UCL.Forms;

namespace DBKit5
{
    public partial class frmCatalogEdit : Form
    {
        AppDataHelper adh;
        public string ExTags { get; set; }
        public string Title { get; set; }
        public int ParentID { get; set; }
        public int PrimaryID { get; set; }
        public Action RefreshHandler { get; set; }
        public frmCatalogEdit()
        {
            InitializeComponent();
        }

        private void frmCatalogEdit_Load(object sender, EventArgs e)
        {
            adh = new AppDataHelper();
            cbbParent.DataSource = adh.ExecuteTreeTable("select ID, Name from tgeneralcatalog where ParentID={0} and ExTags='" + ExTags + "' order by Ordinal", "0");
            cbbParent.DisplayMember = "Name";
            cbbParent.ValueMember = "ID";
            cbbParent.SelectedValue = this.ParentID;

            if (PrimaryID > 0)
            {
                DataTable dt = adh.SelectDataTable("tgeneralcatalog", "ID=" + PrimaryID);
                tbName.Text = dt.GetValue<string>(r => { return r["Name"]; });
                cbbParent.SelectedValue = dt.GetValue<string>(r => { return r["ParentID"];});
                this.ExTags = dt.GetValue<string>(r => { return r["ExTags"];});
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DataModule dm = new DataModule();
            dm.TableName = "tgeneralcatalog";
            dm.DBH = adh;
            dm.AddParam("Name", tbName.Text);
            dm.AddParam("ParentID", cbbParent.GetSelectedValue());
            bool result = false;
            if (PrimaryID > 0)
            {
                result=dm.Update("ID=" + PrimaryID);
            }
            else
            {
                if(!string.IsNullOrEmpty(ExTags)) dm.AddParam("ExTags", this.ExTags);
                result=dm.Insert();
            }
            MessageBox.Show(result ? "保存成功" : dm.GetError());
            if (result)
            {
                // 执行刷新等操作
                if (RefreshHandler != null) RefreshHandler();
                this.Close();
            }
        }
    }
}
